package com.ikingtech.framework.sdk.wechat.embedded.office;

import com.fasterxml.jackson.core.type.TypeReference;
import com.ikingtech.framework.sdk.context.exception.FrameworkException;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.framework.sdk.wechat.embedded.exception.WechatEmbeddedExecptionInfo;
import com.ikingtech.framework.sdk.wechat.embedded.office.resposne.WechatOfficeAuthorizationAccessTokenResponse;
import com.ikingtech.framework.sdk.wechat.embedded.properties.WechatProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 微信相关操作
 *
 * @author tie yan
 */
@Slf4j
@RequiredArgsConstructor
public class WechatOfficeRequest {

    private final WechatProperties properties;


    public List<WechatOfficeInfo> all() {
        return Tools.Coll.convertList(this.properties.getMini(), wechatMiniConfig -> {
            WechatOfficeInfo wechatOfficeInfo = new WechatOfficeInfo();
            wechatOfficeInfo.setWechatOfficeId(wechatMiniConfig.getId());
            wechatOfficeInfo.setWechatOfficeAppId(wechatMiniConfig.getAppId());
            wechatOfficeInfo.setWechatOfficeAppSecret(wechatMiniConfig.getAppSecret());
            wechatOfficeInfo.setWechatOfficeName(wechatMiniConfig.getName());
            return wechatOfficeInfo;
        });
    }

    public WechatOfficeAuthorizationAccessTokenResponse getAuthorizationAccessToken(String wechatMiniId, String code) {
        for (WechatProperties.WechatMini wechatMini : this.properties.getMini()) {
            if (wechatMini.getId().equals(wechatMiniId)) {
                return this.getAuthorizationAccessToken(wechatMini.getAppId(), wechatMini.getAppSecret(), code);
            }
        }
        throw new FrameworkException(WechatEmbeddedExecptionInfo.WECHAT_MINI_NOT_FOUND);
    }

    public WechatOfficeAuthorizationAccessTokenResponse getAuthorizationAccessToken(String appId, String appSecret, String code) {
        String resultStr;
        try {
            resultStr = Tools.Http.get(Tools.Str.format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={}&secret={}}&code={}}&grant_type=authorization_code", appId, appSecret, code));
        } catch (Exception e) {
            throw new FrameworkException(Tools.Str.format("get wechat office authorization access token exception[code={}][exception={}].", code, e.getMessage()));
        }
        if (Tools.Str.isBlank(resultStr)) {
            throw new FrameworkException("get wechat office authorization access token without response." + code);
        }
        return Tools.Json.toBean(resultStr, new TypeReference<>() {});
    }
}
